package de.uni_potsdam.hpi.bpt.ai.diagram;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

public class ShapeFactory {

	protected StencilSet stencilset = null;
	protected Map<String, Shape> cache = null;

	public ShapeFactory(StencilSet stencilset, ArrayList<String> ssextensions) {
		if (null == stencilset) 
			throw new RuntimeException("No stencilset");
		
		this.stencilset = stencilset;
		this.cache = new HashMap<String, Shape>();
	}

	/**
	 * Creates a shape. If applicable, returns a Node
	 * 
	 * @param shapeJson
	 * @return
	 * @throws JSONException
	 */
	public Shape getShape(JSONObject shapeJson) throws JSONException {

		String resourceId = shapeJson.getString("resourceId");

		if (this.cache.containsKey(resourceId)) {
			return this.cache.get(resourceId);
		}

		Shape shape = null;
		StencilType stencilType = null;
		
		if (shapeJson.has("stencil")) {
			JSONObject stencil = shapeJson.getJSONObject("stencil");
			if (stencil.has("id")) {
				stencilType = new StencilType(stencil.getString("id"), this.stencilset);
			}
			
			if (null != stencilType && null != this.stencilset.specification) {
				if (this.stencilset.isNode(stencilType.getId())) {
					shape = new Node(resourceId, stencilType);
				}
				else {
					shape = new Edge(resourceId, stencilType);
				}
			}
		}
		
		if (null == shape) {
			shape = new Shape(resourceId);
		}
		
		this.cache.put(resourceId, shape);

		return shape;
	}
	
	public StencilSet getStencilSet() {
		return this.stencilset;
	}
}
